package cn.maigc.web.sys_user.service.impl;

import cn.maigc.web.sys_menu.entity.AssignTreeParam;
import cn.maigc.web.sys_menu.entity.AssignTreeVo;
import cn.maigc.web.sys_menu.entity.MakeMenuTree;
import cn.maigc.web.sys_menu.entity.SysMenu;
import cn.maigc.web.sys_menu.service.SysMenuService;
import cn.maigc.web.sys_user.entity.SysUser;
import cn.maigc.web.sys_user.mapper.SysUserMapper;
import cn.maigc.web.sys_user.service.SysUserService;
import cn.maigc.web.sys_user_role.entity.SysUserRole;
import cn.maigc.web.sys_user_role.service.SysUserRoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysMenuService sysMenuService;
    @Transactional //事务
    @Override
    public void saveUser(SysUser sysUser) {
        //增加用户信息
        int insert = this.baseMapper.insert(sysUser);
        //判断，设置用户的角色，中间表
        if(insert > 0){
            //前端的数据是用逗号隔开的，拆分
            String[] split = sysUser.getRoleId().split(",");
            //判断
            if(split.length > 0){
                //定义一个用来存储SysUserRole的集合
                List<SysUserRole> roles = new ArrayList<>();
                for (int i = 0; i < split.length; i++) {
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setUserId(sysUser.getUserId());
                    sysUserRole.setRoleId(Long.parseLong(split[i]));
                    roles.add(sysUserRole);
                }
                //保存用户角色表
                sysUserRoleService.saveBatch(roles);

            }
        }
    }

    @Transactional
    @Override
    public void editUser(SysUser sysUser) {
        //修改用户信息
        int i = this.baseMapper.updateById(sysUser);
        //判断 维护用户角色表
        if(i > 0){
            String[] split = sysUser.getRoleId().split(",");
            //删除用户原来的角色
            QueryWrapper<SysUserRole> wrapper = new QueryWrapper<>();
            wrapper.lambda().eq(SysUserRole::getUserId,sysUser.getUserId());
            sysUserRoleService.remove(wrapper);
            //重新增加新的数据
            if(split.length > 0){
                List<SysUserRole> roles = new ArrayList<>();
                for (int j = 0; j < split.length; j++) {
                  SysUserRole sysUserRole = new SysUserRole();
                  sysUserRole.setUserId(sysUser.getUserId());
                  sysUserRole.setRoleId(Long.parseLong(split[j]));
                  roles.add(sysUserRole);
                }
                //保存到用户角色表
                sysUserRoleService.saveBatch(roles);
            }
        }

    }

    @Transactional
    @Override
    public void deleteUser(Long userId) {
        //删除用户表
        int i = this.baseMapper.deleteById(userId);

        if(i > 0){
            //删除用户角色表
            QueryWrapper<SysUserRole> wrapper = new QueryWrapper<>();
            wrapper.lambda().eq(SysUserRole::getUserId,userId);
            sysUserRoleService.remove(wrapper);
        }

    }
    @Override
    public AssignTreeVo getAssignTree(AssignTreeParam param) {
        //查询用户的信息
        SysUser user = this.baseMapper.selectById(param.getUserId());
        List<SysMenu> menuList = null;
        //判断是否是超级管理员
        if(StringUtils.isNotEmpty(user.getIsAdmin()) || "1".equals(user.getIsAdmin())){
            //是超级管理员，查询所有的菜单
            menuList = sysMenuService.list();
        }else{
            menuList = sysMenuService.getMenuByUserId(param.getUserId());
        }
        //组装树
        List<SysMenu> makeTree = MakeMenuTree.makeTree(menuList, 0L);
        //查询角色原来的菜单
        List<SysMenu> roleList = sysMenuService.getMenuByRoleId(param.getRoleId());
        List<Long> ids = new ArrayList<>();
        Optional.ofNullable(roleList).orElse(new ArrayList<>())
                .stream()
                .filter(item -> item != null)
                .forEach(item ->{
                    ids.add(item.getMenuId());
                });
        //组装返回数据
        AssignTreeVo vo = new AssignTreeVo();
        vo.setCheckList(ids.toArray());
        vo.setMenuList(makeTree);
        return vo;
    }
}
